package com.heima.wemedia.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.message.ArticleForEsConstants;
import com.heima.common.constans.message.NewsAutoScanConstants;
import com.heima.common.constans.message.WmNewsMessageConstants;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dto.WmNewsDto;
import com.heima.model.media.dto.WmNewsPageDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service

@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    String fileUrl;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Override
    public ResponseResult findList(WmNewsPageDto dto) {
        //参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //分页条件查询
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery();
        //状态精确查询
        if (dto.getStaus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStaus());
        }

        //频道精准查询
        if (null != dto.getChannelId() ) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (null !=dto.getKeyword()) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //调用线程工具类get方法取出user
        WmUser user = WmThreadLocalUtils.getUser();
        //查询当前登录用户的信息
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "用户不存在");
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        //按照创建日期倒序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        //结果封装返回
        IPage<WmNews> result = page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(result.getCurrent(), result.getSize(), result.getTotal());
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileUrl);
        return responseResult;
    }
     @Autowired
    KafkaTemplate<String,String>kafkaTemplate;
    @Override
    @Transactional
    public ResponseResult summitNews(WmNewsDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查状态字段
        if (!checkNewsStatus(dto.getStatus())) {
            //如果字段不是正常或者已提交返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //利用线程工具类获取user对象并检查user对象,如果不存在返回需要登录的错误
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "用户不存在请登录");
        }
        //dto请求对象数据拷贝到wmnews对象中
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //images字段需要转化为字符串
        List<String> coverImages = dto.getImages(); //获取封面图片列表
        //如果列表存在利用steam流的map循环遍历分割路径利用collect获取路径集合
        if (coverImages != null && !coverImages.isEmpty()) {
            coverImages = coverImages.stream()
                    .map(img -> img.replace(fileUrl, "").trim())
                    .collect(Collectors.toList());//trim去空格
        }
        //用，把每一个图片集合拼接
        String imageStr = StringUtils.join(coverImages, ",");
        //封装
        wmNews.setImages(imageStr);
        //如果文章类型为自动选择图片 初始化文章类型
        if(WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //根据id保存和修改文章
        wmNews.setUserId(user.getId());
        savaOrUpdateWmnews(wmNews);
        //设置内容和封面引用图片和素材的关联
        //抽取出内容中关联的所有图片路径集合
        List<String> imageList =ectractUrlInfo(dto.getContent());
        //如果不是草稿，设置抽取图片与素材关联关系
        //保存图片对应的素材和自媒体文章的关联关系
        if(imageList!=null && imageList.isEmpty()){
            saveRelationInfo(imageList,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        }
        //如果不是草稿，设置封面图片与素材的关联关系
        //如果type是自动，需自动生成封面
        if(imageList!=null&&!imageList.isEmpty()&&WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            coverImages=autoSetCoverImages(wmNews,imageList);
        }
        if(!WmNews.Status.NORMAL.getCode().equals(dto.getStatus())&&coverImages!=null
        && !coverImages.isEmpty()){
            saveRelationInfo(coverImages,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        }
        if(wmNews.getStatus()==1){
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        }
        return ResponseResult.okResult();

    }



    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询文章
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //返回结果
        ResponseResult responseResult = ResponseResult.okResult();
        responseResult.setHost(fileUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //检查参数
        if(id==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"id不能缺少");
        }
        //根据文章id，当前登录用户id 查询文章数据
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId, id)
                .eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId()));
        if(wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断当前文章状态 status==9 enable==1
        if(WmNews.Status.PUBLISHED.equals(wmNews.getStatus())&& wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章未下架无法删除");
        }
        //去除素材与文章的关系
       wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                                  .eq(WmNewsMaterial::getNewsId,id));
        //删除文章
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //检查参数
        if(dto==null || dto.getId()==null ||(dto.getEnable()!=0 && dto.getEnable()!=1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId, dto.getId())
                .eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if(wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }
        //判断文章是否发布
         if(!WmNews.Status.PUBLISHED.getCode().equals(wmNews.getStatus())){
             return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"只有发布状态的文章才可以上下架");
         }
        //修改文章状态，同步到app端
        if(dto.getEnable()!=null && dto.getEnable()>-1 &&dto.getEnable()<2){
            if(wmNews.getArticleId()!=null){
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("enable",dto.getEnable());
                hashMap.put("articleId",wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(hashMap));
            }
            update(
                    Wrappers.<WmNews>lambdaUpdate()
                            .set(WmNews::getEnable,dto.getEnable())
                            .eq(WmNews::getId,dto.getId())
            );
            if(dto.getEnable()==0){
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,wmNews.getArticleId().toString());
            }else {
                kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD,wmNews.getArticleId().toString());
            }
        }


        return ResponseResult.okResult();
    }

    @Override
    public List<Integer> findRelease() {
        //查询状态为8或4 发布时间小于等于当前时间
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery();
        lambdaQueryWrapper.le(WmNews::getPublishTime,new Date())
                .and(q->q.eq(WmNews::getStatus,4).or().eq(WmNews::getStatus,8));
        log.info("查询待发布文章信息：==》{}",lambdaQueryWrapper.getSqlSegment());
        //将查询结果放入集合
        List<WmNews> list = list(lambdaQueryWrapper);
        //利用stream流获取所有集合中id并放入新集合中
        List<Integer> newslist = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return newslist;
    }
  @Autowired
  WmNewsMapper wmNewsMapper;
    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //封装参数
        //查询文章标题
        String title = dto.getTitle();
        if(StringUtils.isNotBlank(title)){
            dto.setTitle("%"+title+"%");
        }
        dto.checkParam();
        Long page = dto.getPage();
        Long size = dto.getSize();
        dto.setPage((page-1)*size);
        //执行分页查询
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        long listCount = wmNewsMapper.findListCount(dto);
        //封装返回结果
        PageResponseResult responseResult = new PageResponseResult((long) page, (long) size, listCount);
        responseResult.setData(listAndPage);
        return responseResult;
    }
    @Autowired
    WmUserMapper wmUserMapper;
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        return wmNewsMapper.findWmNewsVo(id);
    }

    //根据内容中的图片自动生成封面图片列表
    private List<String> autoSetCoverImages(WmNews wmNews, List<String> imageList) {
        int size = imageList.size();
          List<String> coverImages = new ArrayList<>();
          if(size>2){
              //图片数量大于2 为多图 截取列表前三张做封面
              coverImages = imageList.stream().limit(3).collect(Collectors.toList());
          }else if(size>0&&size<=2){
              //type为单图 截取列表第一张做封面
              coverImages = imageList.stream().limit(1).collect(Collectors.toList());
              wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
          }else {
              //type为0 无图
              wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
          }
          //如果图片列表存在，将每个图片地址用，拼接成一个新的字符串
          if(!coverImages.isEmpty()){
              wmNews.setImages(StringUtils.join(coverImages,","));
          }
          updateById(wmNews); //修改文章
        //返回文章封面列表集合 用于设置关联
        return imageList;
    }

    //保存图片对应的素材和自媒体文章关联关系
    private void saveRelationInfo(List<String> imageList, Integer newsId, Short type) {
        //根据当前登录用户Id及图片列表 查询出所有对应素材信息
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .in(WmMaterial::getUrl, imageList)
        );
        if(wmMaterials==null || wmMaterials.isEmpty()){
            throw  new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关联素材不存在"));
        }
        //判断当前图片 在素材库中是否存在，不如不存在抛异常
            List<Integer> materialIds = new ArrayList<>();
        //将素材信息转换为map集合 url作为key id为value 封装成一个map集合
        Map<String, Integer> urlAndIds = wmMaterials.stream().collect(
                Collectors.toMap(wmMaterial -> wmMaterial.getUrl(),
                        wmMaterial -> wmMaterial.getId())
        );
        for (int i = 0; i < imageList.size(); i++) {
            String currentImg = imageList.get(i);
            if(urlAndIds.containsKey(currentImg)){
                throw  new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在"));
            }
            materialIds.add(urlAndIds.get(currentImg));
        }
        //根据素材id文章id引用类型 将关联数据保存到数据库
        wmNewsMaterialMapper.saveRelationsByContent(materialIds,newsId,type);
    }


    //抽取文章内容中关联的图片
    private List<String> ectractUrlInfo(String content) {
       List<String> imagesList = new ArrayList<>();
       //利用jsonArry将json数据content转换为集合数组
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        //遍历数组如果获取的图片类型与数据库一致，去除图片地址加入图片集合中
        for (Map map : maps) {
            if(WemediaContans.WM_NEWS_TYPE_IMAGE.equals(map.get("type"))){
                String imgUrl = (String) map.get("value");
                imagesList.add(imgUrl.replace(fileUrl,""));
            }
        }
        return imagesList;
    }


     //保存或者修改自媒体文章
    private void savaOrUpdateWmnews(WmNews wmNews) {
        //补全参数
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);
        //如果文章不存在
        if(wmNews.getId()==null){
            save(wmNews);
        }else {
            //根据文章id删除相关素材关联
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId())
            );
            //修改
            updateById(wmNews);
        }
    }

    //检查状态字段
    private boolean checkNewsStatus(Short status) {
        //判断当前字段是否为正常或者已提交
        if (status != null && (status.equals(WmNews.Status.NORMAL.getCode()))
                || status.equals(WmNews.Status.SUBMIT.getCode())) {
            return true;
        }
        return false;
    }


}
